//
//  OnLineViewController.swift
//  豆瓣电台.Swift
//
//  Created by rongfeng on 16/3/1.
//  Copyright © 2016年 rongfeng. All rights reserved.
//

import UIKit
import AVFoundation

class OnLineViewController: UIViewController,AVAudioPlayerDelegate {

    
    var channel:Channel! //当前频道
    var songList:Array<Song> = [] //当前频道的歌曲
    var curIndex:Int!
    var CurSong:Song!
    var player: AVAudioPlayer! //播放器
    var timer:NSTimer! //定时器
    
    
    
    //收藏
    @IBAction func ShouChang(sender: AnyObject) {
        
        let song = self.CurSong;
        //NSKeyedArchiver.archiveRootObject(song, toFile: "/Users/rongfeng/Desktop/test.plist")
        
    }
    
    @IBOutlet weak var songImageView: UIImageView!
    
    @IBOutlet weak var slider: UISlider!
    
    @IBOutlet weak var aritistLabel: UILabel!
    
    
    @IBOutlet weak var songName: UILabel!
    
    
    @IBOutlet weak var PerBtn: UIButton!
    @IBOutlet weak var PlayBtn: UIButton!
    @IBOutlet weak var NextBtn: UIButton!
    @IBOutlet weak var timeLabel: UILabel!
    
    @IBAction func ValueChaneged(sender: UISlider) {
        
        player.currentTime = NSTimeInterval(sender.value) * player.duration;
        
    }
    //上一曲
    @IBAction func PreClicked(sender: AnyObject) {
        var index = self.curIndex - 1;
        loadSongWithIndex(index);
        
    }
    
    //播放
    @IBAction func PallAction(sender: AnyObject) {
        
        //暂停
        //self.player.stop();
        
        if self.player.playing {
            player.pause();
            
        }else {
            player.play();
        }
    }
    
    func loadSongWithIndex(index:Int) {
        
        //let index = self.curIndex + 1;
        if index < self.songList.count && index >= 0{
            
            self.CurSong = self.songList[index]
            self.curIndex = index;
            self.LoadSongInfo(self.CurSong.id);
            
        }

    }
    
    //下一曲
    @IBAction func NextAction(sender: AnyObject) {
        
        self.NextBtn.enabled = false;
        let index = self.curIndex + 1;
        self.player.stop();
        if index < self.songList.count {
            
            self.CurSong = self.songList[index]
            self.curIndex = index;
            self.LoadSongInfo(self.CurSong.id);
            
        }
    }
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        
        LoadSongList();
        
        //player = AVAudioPlayer!;
        
        print("OnLineViewController");
        // Do any additional setup after loading the view.
    }
    //播放歌曲
    func playSong(data: NSData) {
        
//        if player!.playing {
//            player.stop();
//        }
        //player.stop();
//        if player.playing {
//            print("正在播放音乐!");
//        }
        player = try!AVAudioPlayer(data: data);
        
        player.prepareToPlay();
        player.play();
        player.delegate = self;
        timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: "refreshSlider", userInfo: nil, repeats: true);
    
    }
    //更新滑块(进度)
    func refreshSlider() {
        
        slider.value = Float(player.currentTime / player.duration);
        
        
    }
    //播放完成后
    func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool) {
        //停止滑动
        timer.invalidate();
        //下一曲
        let index = self.curIndex + 1;
        if index < self.songList.count {
            
            self.CurSong = self.songList[index]
            self.curIndex = index;
            self.LoadSongInfo(self.CurSong.id);
            
        }
        
    }
    
//下载歌曲
    func downLoadSong(path:String) {
        
      if path.characters.count > 180 {
            //下一曲
            let index = self.curIndex + 1;
            if index < self.songList.count {
                
                self.CurSong = self.songList[index]
                self.curIndex = index;
                self.LoadSongInfo(self.CurSong.id);
                
            }
      } else {
        let url = NSURL(string: path);
        let request = NSURLRequest(URL: url!);
        let  mainQuene = NSOperationQueue.mainQueue();
        NSURLConnection.sendAsynchronousRequest(request, queue: mainQuene) { (response, Data, error) -> Void in
            let httpresponse = response as! NSHTTPURLResponse;
            
            if httpresponse.statusCode == 200 {
                _ = NSString(data: Data!, encoding: NSUTF8StringEncoding);
                //print("网络歌曲：\(str)");
                self.playSong(Data!);
                
            }
            else {
                
            }
        }
    }
        
}
    
    
    //获取歌曲信息
    func LoadSongInfo(id :Int) {
        
        
        
        let url = NSURL(string: "http://music.baidu.com/data/music/fmlink?type=mp3&rate=1&format=json&songIds=\(id)");
        let request = NSURLRequest(URL: url!);
        let  mainQuene = NSOperationQueue.mainQueue();
        NSURLConnection.sendAsynchronousRequest(request, queue: mainQuene) { (response, Data, error) -> Void in
            let httpresponse = response as! NSHTTPURLResponse;
            
            if httpresponse.statusCode == 200 {
                let str = NSString(data: Data!, encoding: NSUTF8StringEncoding);
                //print("网络歌曲：\(str)");
                //将JSON转化为字符串
                
                let dict:NSDictionary = try! NSJSONSerialization.JSONObjectWithData(Data!, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary;
                print("歌曲信息:\(dict)");
                //查找需要的歌曲
                let dataDic:NSDictionary = dict["data"] as! NSDictionary
                let list: NSArray = dataDic["songList"] as! NSArray;
                let songDict:NSDictionary = list[0] as! NSDictionary;
                
                self.CurSong.refreshSong(songDict);
                
                self.showSongInfo();
                
                //
                let Linkstr = self.CurSong.songLink as String;
                print("歌曲连接:\(self.CurSong.songLink)\n 歌曲字符长度:\(Linkstr.characters.count)");
                
                //下载歌曲
                self.downLoadSong((self.CurSong.songLink as? String)!);
                print("\(self.CurSong.songName)");

            }
            else {
                
            }
        }
        
        self.NextBtn.enabled = true;
    }
    
    //获取歌曲列表
    func LoadSongList() {
        
        var url = NSURL(string: "http://fm.baidu.com/dev/api/?tn=playlist&special=flash&prepend=&format=json&_=1378945264366&id=" + String(channel.id));
        var request = NSURLRequest(URL: url!);
        var  mainQuene = NSOperationQueue.mainQueue();
        NSURLConnection.sendAsynchronousRequest(request, queue: mainQuene) { (response, Data, error) -> Void in
            var httpresponse = response as! NSHTTPURLResponse;
            
            if httpresponse.statusCode == 200 {
                let str = NSString(data: Data!, encoding: NSUTF8StringEncoding);
                //print("网络歌曲：\(str)");
                //将JSON转化为字符串
                
                let songdic:NSDictionary =
                try! NSJSONSerialization.JSONObjectWithData(Data!, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary;
                //print("字典:\(songdic)");
                
                var songarray:NSArray = songdic["list"] as! NSArray;
                
                for dic :AnyObject in songarray {
                    
                    var song = Song();
                    var num:NSNumber = dic["id"] as! NSNumber;
                    song.id = num.integerValue;
                    self.songList.append(song);
                    
                }
                if self.songList.count != 0 {
                    
                    self.CurSong = self.songList[0];
                    self.curIndex = 0;
                    self.LoadSongInfo(self.CurSong.id);
                }
                print("歌曲列表:\(self.songList)");
            }
            else {
                
            }
        }
    }
    
    //显示歌曲信息
    
    func showSongInfo() {
        
        self.aritistLabel.text = self.CurSong.artistName as NSString as String ;
        self.songName.text = self.CurSong.songName as NSString as String;
        let url = NSURL(string: self.CurSong.songPicBig as String);
        let imgstr = self.CurSong.songPicBig as String;
        print("图片信息:\(url)\n 长度:\(imgstr.characters.count)");
        
        //如果图片信息加载失败，则下一曲播放!
        if imgstr.characters.count <= 0 {
            //下一曲
            let index = self.curIndex + 1;
            if index < self.songList.count {
                
                self.CurSong = self.songList[index]
                self.curIndex = index;
                self.LoadSongInfo(self.CurSong.id);
                
            }
        }
        let data = NSData(contentsOfURL: url!);
        let image = UIImage(data: data!);
        self.songImageView.image = image;
        
        //self.songImageView.image = UIImage(data: NSData(contentsOfFile: NSURL(string: self.CurSong.songPicBig as String)));
        
    }
    
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
